package net.pimpas.web.tomcat.serviceprovider.scanner;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.pimpas.core.configuration.file.FileConfiguration;
import net.pimpas.core.configuration.file.FileConfigurationImpl;
import net.pimpas.core.scanner.Scanner;
import net.pimpas.core.scanner.exception.ScannerException;
import net.pimpas.logging.serviceprovider.LoggingServiceProvider;
import net.pimpas.logging.serviceprovider.LoggingServiceProviderFactoryImpl;

public class TomcatServiceProviderScanner implements Scanner<FileConfiguration> {
	
	private FileConfiguration fileConfiguration;
	private LoggingServiceProvider logger = LoggingServiceProviderFactoryImpl.getLoggingServiceProvider(TomcatServiceProviderScanner.class);

	public String getName() {
		return this.getClass().getSimpleName();
	}

	@SuppressWarnings("unchecked")
	public List<FileConfiguration> getResult() {
		List t = new ArrayList<FileConfiguration>();
		t.add(this.getFileConfiguration());
		return t;
	}

	public void scan() throws ScannerException {
		logger.debug("Looking for configuration file: pimpas-tomcat-config.xml");
		URL url = this.getClass().getClassLoader().getResource("pimpas-tomcat-config.xml");
		if(url== null) {
			// try default
			url = this.getClass().getClassLoader().getResource("pimpas-tomcat-config-default.xml");
			if(url == null)
				// error
				throw new ScannerException("Cannot FIND Tomcat Configuration File");
			logger.info("[TOMCAT]: File pimpas-tomcat-config.xml not found, using default!");
		}
		
		InputStream stream = null;
		try {
			stream = url.openStream();
			logger.debug("Setting Tomcat Configuration File: "+url.getFile());
			
			FileConfiguration fc = new FileConfigurationImpl(url, stream);
			this.setFileConfiguration(fc);
		} catch (IOException e) {
			throw new ScannerException(e);
		}
	}

	public FileConfiguration getFileConfiguration() {
		return fileConfiguration;
	}

	public void setFileConfiguration(FileConfiguration fileConfiguration) {
		this.fileConfiguration = fileConfiguration;
	}
}